<script setup lang="ts">
const props = defineProps({
  content: {
    type: String,
    default: '',
  },
  initPosition: {
    type: Object,
    default: () => {
      return {
        top: 400,
        left: 300,
      }
    },
  },
})
const emit = defineEmits(['operate'])
const isDragging = ref(false)
const position = ref(props.initPosition)
const initialMousePos = ref({ x: 0, y: 0 })
let x = 0 // 水平距离
let y = 0 // 垂直距离
function startDrag(event: any) {
  isDragging.value = true;
  x = event.currentTarget.offsetLeft
  y = event.currentTarget.offsetTop
  initialMousePos.value.x = event.touches[0].clientX - position.value.left
  initialMousePos.value.y = event.touches[0].clientY - position.value.top
}
function drag(event: any) {
  if (isDragging) {
    position.value.left = event.touches[0].clientX - initialMousePos.value.x
    position.value.top = event.touches[0].clientY - initialMousePos.value.y
  }
}
function stopDrag(event: any) {
  isDragging.value = false
  // 移动距离小于5触发点击事件
  if ((Math.abs(event.currentTarget.offsetLeft - x) < 5 && Math.abs(event.currentTarget.offsetTop - y) < 5)) {
    handleButtonClick()
  }
}
function handleButtonClick() {
  // 处理按钮点击事件
  emit('operate')
}
</script>

<template>
  <view class="floating-button-wrapper" :style="{ top: position.top + 'px', left: position.left + 'px' }"
    @touchstart.stop="startDrag" @touchend.stop="stopDrag" @touchmove.stop="drag">
    <template v-if="props.content">{{ props.content }}</template>
    <template v-else>
      <img class="w-36rpx h-36rpx" src="../../static/plus.png" alt="" />
      <!-- <u-icon name="plus" size="30" color="#fff"></u-icon> -->
    </template>
  </view>
</template>

<style lang="scss" scoped>
.floating-button-wrapper {
  box-sizing: border-box;
  position: fixed;
  right: 12px;
  width: 120rpx;
  height: 120rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  z-index: 100;
  border-radius: 50%;
  padding: 8px;
  color: #fff;
  font-size: 12px;
  background: $theme-color;
  // box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.16), 0px -2px 4px 0px rgba(0, 0, 0, 0.1);
  box-shadow: 4px 4px 4px 0px #00000040;
  opacity: 0.8;
  font-weight: bold;
  font-weight: 800;
}
</style>
